<template>
  <div class="login-page-wrapper">
    <div class="login-card" ref="loginCardRef">
      <div class="card-header">
        <h2 class="login-title">溃疡性结肠炎智能评分系统</h2>
        <p class="login-subtitle">EndoSight-UC 医生工作站</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="large"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入工号"
            prefix-icon="User"
            clearable
            :disabled="loginState.loading"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            :type="loginState.showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            prefix-icon="Lock"
            :suffix-icon="loginState.showPassword ? 'View' : 'Hide'"
            :disabled="loginState.loading"
            @keyup.enter="handleLogin"
            @click-right-icon="togglePasswordVisibility"
          >
            <template #suffix>
              <el-icon
                class="password-toggle"
                :class="{ 'password-toggle--visible': loginState.showPassword }"
                @click="togglePasswordVisibility"
              >
                <View v-if="loginState.showPassword" />
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item class="login-button">
          <el-button
            type="primary"
            size="large"
            :loading="loginState.loading"
            :disabled="loginState.loading"
            @click="handleLogin"
            @mousedown="handleButtonClick"
            class="submit-button"
          >
            <template v-if="!loginState.loading">
              <span class="button-content">登录</span>
            </template>
            <template v-else>
              <span class="button-content">
                <el-icon class="loading-icon">
                  <Loading />
                </el-icon>
                登录中...
              </span>
            </template>
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <el-divider>
          <span class="footer-text">测试账号信息</span>
        </el-divider>
        <TestAccountInfo
          username="admin"
          password="admin123"
          @fill="handleAccountFill"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createShake, createRipple } from '@/utils/animations'
import { View, Hide, Loading } from '@element-plus/icons-vue'
import TestAccountInfo from '@/components/TestAccountInfo.vue'

// TypeScript接口定义
interface LoginForm {
  username: string
  password: string
}

interface LoginState {
  loading: boolean
  showPassword: boolean
  error: string | null
  animationReady: boolean
}

const store = useStore()
const router = useRouter()
const route = useRoute()

// 响应式引用
const loginFormRef = ref()
const loginCardRef = ref<HTMLElement>()

// 登录状态管理
const loginState = reactive<LoginState>({
  loading: false,
  showPassword: false,
  error: null,
  animationReady: false
})

// 表单数据
const loginForm = reactive<LoginForm>({
  username: 'admin',
  password: 'admin123'
})

// Element Plus表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 微交互处理函数
const handleButtonClick = (event: MouseEvent) => {
  const button = event.currentTarget as HTMLElement
  createRipple(button, event)
}

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('已复制到剪贴板')
    } catch (error) {
      ElMessage.error('复制失败')
    }
    document.body.removeChild(textArea)
  }
}

// 处理TestAccountInfo组件的自动填充事件
const handleAccountFill = (field: 'username' | 'password', value: string) => {
  nextTick(() => {
    loginForm[field] = value
  })
}

// 登录处理函数（带动画反馈）
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) {
      // 表单验证失败时震动效果
      if (loginCardRef.value) {
        createShake(loginCardRef.value)
      }
      return
    }

    loginState.loading = true
    loginState.error = null

    const result = await store.dispatch('auth/login', {
      username: loginForm.username,
      password: loginForm.password
    })

    if (result.success) {
      ElMessage.success('登录成功')

      // 获取重定向地址
      const redirect = route.query.redirect as string || '/scoring/new'
      router.push(redirect)
    } else {
      loginState.error = result.message || '登录失败'
      ElMessage.error(loginState.error)

      // 登录失败时震动效果
      if (loginCardRef.value) {
        createShake(loginCardRef.value)
      }
    }
  } catch (error) {
    console.error('Login error:', error)
    loginState.error = '登录过程中发生错误，请稍后重试'
    ElMessage.error(loginState.error)

    // 异常时震动效果
    if (loginCardRef.value) {
      createShake(loginCardRef.value)
    }
  } finally {
    loginState.loading = false
  }
}

// 密码显示/隐藏切换
const togglePasswordVisibility = () => {
  loginState.showPassword = !loginState.showPassword
}

// 组件挂载
onMounted(() => {
  loginState.animationReady = true
})
</script>

<style scoped>
/* 登录页面包装器 - 实现完美居中 */
.login-page-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: var(--aperture-space-4); /* 移动端呼吸空间 */
}

.login-card {
  /* 卡片尺寸限制 - 这才是应该限制宽度的东西！ */
  width: 100%;
  max-width: 420px;

  /* 🍎 真正的苹果毛玻璃三件套 */

  /* 1. 材质的底色：极淡的半透明白色 */
  background: rgba(255, 255, 255, 0.28);

  /* 2. 核心：背景模糊 (毛玻璃效果) */
  backdrop-filter: blur(20px) saturate(180%);
  -webkit-backdrop-filter: blur(20px) saturate(180%); /* Safari兼容 */

  /* 3. 精致的玻璃边框 */
  border: 1px solid rgba(255, 255, 255, 0.18);

  /* 🍎 苹果风格阴影 - 柔和、弥散、带颜色 */
  box-shadow:
    0 8px 32px rgba(31, 38, 135, 0.12),
    0 20px 60px rgba(120, 119, 198, 0.08),
    0 0 0 1px rgba(255, 255, 255, 0.1);

  border-radius: var(--aperture-radius-xl);
  transition: all var(--aperture-duration-normal) var(--aperture-ease-out);
  animation: cardEntrance 0.8s var(--aperture-ease-out);
}

/* 卡片入场动画 */
@keyframes cardEntrance {
  0% {
    opacity: 0;
    transform: translateY(40px) scale(0.9);
    filter: blur(2px);
  }
  50% {
    opacity: 0.8;
    transform: translateY(-5px) scale(1.01);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
    filter: blur(0);
  }
}

/* 卡片悬停效果 */
.login-card:hover {
  transform: translateY(-2px) scale(1.01);
  box-shadow:
    0 0 0 1px rgba(255, 255, 255, 0.15),
    0 12px 40px rgba(0, 0, 0, 0.15),
    0 25px 75px rgba(31, 38, 135, 0.2);
}

.card-header {
  text-align: center;
  padding: var(--aperture-space-8) var(--aperture-space-6) var(--aperture-space-4);
}

.login-title {
  font-size: var(--aperture-text-2xl);
  font-weight: var(--aperture-font-semibold);
  /* 🍎 苹果风格：在毛玻璃上使用纯白文字确保高对比度 */
  color: #FFFFFF;
  margin: 0 0 var(--aperture-space-2) 0;
  line-height: var(--aperture-leading-tight);
  letter-spacing: -0.02em;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); /* 轻微阴影增强可读性 */
  animation: titleFadeIn 0.6s var(--aperture-ease-out) 0.3s both;
}

.login-subtitle {
  /* 🍎 副标题使用稍柔和但依然清晰的白色 */
  color: rgba(255, 255, 255, 0.9);
  margin: 0 0 var(--aperture-space-6) 0;
  font-size: var(--aperture-text-sm);
  font-weight: var(--aperture-font-normal);
  animation: subtitleFadeIn 0.6s var(--aperture-ease-out) 0.4s both;
}

@keyframes titleFadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes subtitleFadeIn {
  from {
    opacity: 0;
    transform: translateY(-8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-form {
  padding: 0 var(--aperture-space-6) var(--aperture-space-6);
}

/* Element Plus 输入框优化覆盖 - 毛玻璃风格 */
.login-form :deep(.el-input__wrapper) {
  border-radius: var(--aperture-radius-lg);
  border: 1px solid rgba(255, 255, 255, 0.3);
  /* 🍎 输入框也使用半透明白色，与卡片材质一致 */
  background-color: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(10px);
  padding: var(--aperture-space-4);
  transition: all var(--aperture-duration-normal) var(--aperture-ease-out);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: var(--aperture-space-3);
  animation: inputEntrance 0.5s var(--aperture-ease-out) both;
}

.login-form :deep(.el-input__wrapper:nth-child(1)) {
  animation-delay: 0.5s;
}

.login-form :deep(.el-input__wrapper:nth-child(2)) {
  animation-delay: 0.6s;
}

@keyframes inputEntrance {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.login-form :deep(.el-input__wrapper:hover) {
  border-color: rgba(255, 255, 255, 0.6);
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  border-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
  /* 🍎 聚焦时稍微增加不透明度，提升可读性 */
  background-color: rgba(255, 255, 255, 0.25);
}

.login-form :deep(.el-input__inner) {
  font-size: var(--aperture-text-base);
  /* 🍎 输入框文字使用纯白确保在毛玻璃背景上的可读性 */
  color: #FFFFFF;
  font-weight: var(--aperture-font-normal);
}

.login-form :deep(.el-input__inner::placeholder) {
  /* 🍎 占位符使用柔和的白色 */
  color: rgba(255, 255, 255, 0.7);
  font-weight: var(--aperture-font-light);
}

.login-button {
  margin: var(--aperture-space-6) 0 var(--aperture-space-4);
  animation: buttonEntrance 0.5s var(--aperture-ease-out) 0.7s both;
}

@keyframes buttonEntrance {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.submit-button {
  width: 100%;
  height: 48px;
  font-size: var(--aperture-text-base);
  font-weight: var(--aperture-font-semibold);
  border-radius: var(--aperture-radius-lg);
  /* 🍎 苹果风格按钮：使用纯色而非渐变 */
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #6B46C1; /* 使用与背景协调的紫色 */
  letter-spacing: 0.02em;
  position: relative;
  overflow: hidden;
  transition: all var(--aperture-duration-normal) var(--aperture-ease-out);
  backdrop-filter: blur(8px);
  /* 🍎 苹果风格文字阴影 */
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.submit-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left var(--aperture-duration-slow) var(--aperture-ease-out);
}

.submit-button:hover::before {
  left: 100%;
}

.submit-button:hover {
  transform: translateY(-2px) scale(1.02);
  /* 🍎 苹果风格悬停：增强不透明度和阴影 */
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 12px 25px rgba(107, 70, 193, 0.15), 0 4px 12px rgba(255, 255, 255, 0.3);
  color: #5B3CC0; /* 悬停时稍微加深颜色 */
}

.submit-button:active {
  transform: translateY(0) scale(0.98);
  background: rgba(255, 255, 255, 0.85);
  box-shadow: 0 4px 12px rgba(255, 255, 255, 0.2);
  color: #4B2A9E; /* 激活时进一步加深颜色 */
}

/* 按钮内容样式 */
.button-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--aperture-space-2);
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 密码显示/隐藏切换图标 */
.password-toggle {
  cursor: pointer;
  color: var(--aperture-text-tertiary);
  transition: all var(--aperture-duration-fast) var(--aperture-ease-out);
  padding: var(--aperture-space-1);
  border-radius: var(--aperture-radius-sm);
  margin-right: var(--aperture-space-1);
}

.password-toggle:hover {
  color: var(--aperture-primary);
  background-color: rgba(0, 122, 255, 0.1);
  transform: scale(1.1);
}

.password-toggle--visible {
  color: var(--aperture-primary);
}

/* 错误状态样式 */
.login-form :deep(.el-form-item.is-error .el-input__wrapper) {
  border-color: var(--aperture-error);
  box-shadow: 0 0 0 3px rgba(255, 59, 48, 0.1);
  animation: errorShake 0.4s var(--aperture-ease-out);
}

@keyframes errorShake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-2px); }
  20%, 40%, 60%, 80% { transform: translateX(2px); }
}

/* Element Plus 加载状态优化 */
.login-form :deep(.el-button.is-loading) {
  pointer-events: none;
}

.login-form :deep(.el-button.is-loading .el-icon) {
  font-size: 16px;
  margin-right: var(--aperture-space-2);
}

.login-footer {
  padding: var(--aperture-space-6);
  /* 🍎 边界线使用半透明白色，与毛玻璃材质一致 */
  border-top: 1px solid rgba(255, 255, 255, 0.15);
  /* 更半透明的底部区域 */
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(8px);
  border-radius: 0 0 var(--aperture-radius-xl) var(--aperture-radius-xl);
  animation: footerFadeIn 0.5s var(--aperture-ease-out) 0.8s both;
}

@keyframes footerFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.footer-text {
  /* 🍎 footer文字使用柔和的白色，确保在毛玻璃背景上的可读性 */
  color: rgba(255, 255, 255, 0.8);
  font-size: var(--aperture-text-xs);
  font-weight: var(--aperture-font-medium);
  letter-spacing: 0.05em;
  text-transform: uppercase;
}

/* 响应式设计优化 */
@media (max-width: 480px) {
  .login-page-wrapper {
    padding: var(--aperture-space-3);
  }

  .login-card {
    max-width: 100%;
  }

  .login-title {
    font-size: var(--aperture-text-xl);
  }

  .card-header {
    padding: var(--aperture-space-6) var(--aperture-space-4) var(--aperture-space-3);
  }

  .login-form {
    padding: 0 var(--aperture-space-4) var(--aperture-space-4);
  }

  .login-footer {
    padding: var(--aperture-space-4);
  }

  .submit-button {
    height: 44px;
    font-size: var(--aperture-text-sm);
  }

  .login-card:hover {
    transform: none;
    box-shadow:
      0 0 0 1px rgba(255, 255, 255, 0.1),
      0 8px 32px rgba(0, 0, 0, 0.12),
      0 20px 60px rgba(31, 38, 135, 0.15);
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .login-card {
    background: rgba(30, 30, 30, 0.85);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }

  .login-form :deep(.el-input__wrapper) {
    background-color: rgba(60, 60, 60, 0.9);
    border-color: rgba(255, 255, 255, 0.1);
  }

  .login-form :deep(.el-input__inner) {
    color: var(--aperture-text-primary);
  }

  .login-footer {
    background: rgba(40, 40, 40, 0.5);
    border-top-color: rgba(255, 255, 255, 0.1);
  }

  .test-info strong {
    background: rgba(0, 122, 255, 0.2);
  }

  .test-info strong:hover {
    background: rgba(0, 122, 255, 0.3);
  }
}

/* 减少动画偏好支持 */
@media (prefers-reduced-motion: reduce) {
  *,
  *::before,
  *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
}
</style>